const router = require("koa-router")();
const { SuccessModel, FailModel } = require("../utils/model_adapter");
const AccountModel = require("../models/account-model");

router.prefix("/chat");

// 登录
router.post("/login", async (ctx, next) => {
  const { user, pwd, type } = ctx.request.body;
  if (!user) {
    return (ctx.body = new FailModel("user 参数错误", { code: 400 }));
  }
  if (!pwd) {
    return (ctx.body = new FailModel("pwd 参数错误", { code: 400 }));
  }
  if (!type) {
    return (ctx.body = new FailModel("type 参数错误", { code: 400 }));
  }
  const res = await AccountModel.findOne({ where: { account: user } });
  if (res) {
    if (res.pwd == pwd) {
      return (ctx.body = new SuccessModel("登录成功", {
        data: res.dataValues,
      }));
    }
    return (ctx.body = new FailModel("密码错误", { code: 401 }));
  } else {
    await AccountModel.create({
      account: user,
      card_program_type: type,
      pwd,
    });
    const res = await AccountModel.findOne({ where: { account: user } });

    return (ctx.body = new SuccessModel("登录成功", {
      data: res.dataValues,
    }));
  }
});

// 查询客服id是否存在
router.get("/is_exist_admin", async (ctx, next) => {
  const { id } = ctx.query;
  if (!id) {
    return (ctx.body = new FailModel("id 参数错误", { code: 400 }));
  }
  const res = await AccountModel.findOne({
    where: { account: id },
    attributes: ["id", "card_program_type", "account"],
  });
  if (res) {
    return (ctx.body = new SuccessModel("success", {
      data: {
        flag: true,
        info: res.dataValues,
      },
    }));
  }
  return (ctx.body = new SuccessModel("success", {
    data: {
      flag: false,
      info: {},
    },
  }));
});

// 获取客服
router.get("/admin_list", async (ctx, next) => {
  const res = await AccountModel.findAndCountAll({
    attributes: ["id", "card_program_type", "account"],
  });
  return (ctx.body = new SuccessModel("success", {
    data: res,
  }));
});

module.exports = router;
